package com.example.for_screen;

import android.hardware.display.DisplayManager;
import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaFormat;
import android.view.Surface;

import java.nio.ByteBuffer;

public class H264Player implements SocketLive.SocketCallback{

    private MediaCodec mediaCodec;
    public H264Player(Surface surface) {
        try {
//            MediaFormat format = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_HEVC,width,height);
            MediaFormat format = MediaFormat.createVideoFormat("video/avc",720,1280);
            format.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);
            format.setInteger(MediaFormat.KEY_BIT_RATE, 720 * 1280);
            format.setInteger(MediaFormat.KEY_FRAME_RATE, 20);
            format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1);
//            mediaCodec = MediaCodec.createEncoderByType("video/hevc");
            mediaCodec = MediaCodec.createDecoderByType(MediaFormat.MIMETYPE_VIDEO_AVC);
            mediaCodec.configure(format, surface,null, 0);
            mediaCodec.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void callBack(byte[] buf) {
        int index = mediaCodec.dequeueInputBuffer(1000);
        if (index >= 0){
            ByteBuffer inputBuffer = mediaCodec.getInputBuffer(index);
            inputBuffer.clear();
            inputBuffer.put(buf,0,buf.length);
            mediaCodec.queueInputBuffer(index,0,buf.length,System.currentTimeMillis(),0);
            MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
            int outputBufferIndex = mediaCodec.dequeueOutputBuffer(bufferInfo,10000);
            while (outputBufferIndex>= 0){
                mediaCodec.releaseOutputBuffer(outputBufferIndex,true);
                outputBufferIndex = mediaCodec.dequeueOutputBuffer(bufferInfo, 0);

            }
        }
    }
}
